package com.example.cricketscorer.client.presenter;

import java.util.List;

import com.example.cricketscorer.client.CricketScorerEventBus;
import com.example.cricketscorer.client.ScorerServiceAsync;
import com.example.cricketscorer.client.bean.BatsmanBean;
import com.example.cricketscorer.client.bean.PlayerBean;
import com.example.cricketscorer.client.view.BattingView;
import com.example.cricketscorer.client.widget.interfaces.ITable;
import com.example.cricketscorer.client.widget.interfaces.IWidget;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.inject.Inject;
import com.mvp4g.client.annotation.Presenter;
import com.mvp4g.client.presenter.BasePresenter;

@Presenter(view = BattingView.class)
public class BattingPresenter extends BasePresenter<BattingPresenter.IBattingView, CricketScorerEventBus> {
	
	public interface IBattingView extends IWidget {
		ITable getTable();
	}
	
	private List<PlayerBean> players;
	
	private List<BatsmanBean> batsmen;
	
	@Inject
	private ScorerServiceAsync service;
	
	public void setService(ScorerServiceAsync service) {
		this.service = service;
	}

	public void onStart() {
		System.out.println("Inside BattingPresenter.onstart()");
		service.getPlayers("1", new AsyncCallback<List<PlayerBean>>() {

			public void onFailure( Throwable caught ) {
				System.out.println("Inside BattingPresenter.onfailure");
				caught.printStackTrace();
			}

			public void onSuccess( List<PlayerBean> result ) {
				System.out.println("Inside BattingPresenter.onSuccess " + result.size());
				setPlayers( result );
				eventBus.changeBattingWidget( view );
			}

		} );
		//setVisibleConfirmDeletion( false );
	}
	
	private void setPlayers(List<PlayerBean> players) {
		this.players = players;
		//select first two batsmen by default
		selectPlayer(this.players.get(0), 1);
		selectPlayer(this.players.get(1), 2);
	}
	
	public void selectPlayer(PlayerBean player, int row) {
		BatsmanBean batsman = new BatsmanBean(player);
		selectBatsman(batsman, row);
	}
	
	void selectBatsman( BatsmanBean batsman, int row ) {
		ITable table = view.getTable();
		table.setText( row, 0, batsman.getName());
		table.setText( row, 1, String.valueOf(batsman.getRunsScored()));
		table.setText( row, 2, String.valueOf(batsman.getBallsFaced()));
		table.setText( row, 3, String.valueOf(batsman.getFours()));
		table.setText( row, 4, String.valueOf(batsman.getSixes()));
	}
}
